<script setup>
import { Head, usePage, router } from '@inertiajs/vue3'
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'
import SpotlightLayout from '@/Layouts/SpotlightLayout.vue'
import Container from '@/Components/Spotlight/Container.vue'
import Photos from '@/Components/Spotlight/Photos.vue'
import ArticleCard from '@/Components/Spotlight/ArticleCard.vue'
import Newsletter from '@/Components/Spotlight/Newsletter.vue'
import Resume from '@/Components/Spotlight/Resume.vue'
import SocialLink from '@/Components/Spotlight/SocialLink.vue'
import Button from '@/Components/Spotlight/Button.vue'
import PageHero from '@/Components/Spotlight/PageHero.vue'
import LoadingSpinner from '@/Components/UI/LoadingSpinner.vue'
import { XIcon, InstagramIcon, GitHubIcon, LinkedInIcon } from '@/Components/Spotlight/SocialIcons.js'
import { PlusIcon } from '@heroicons/vue/20/solid'

const props = defineProps({
    posts: {
        type: Object,
    required: true,
    },
    filters: {
        type: Object,
    default: () => ({}),
  },
})

const page = usePage()

const canCreatePost = computed(() => Boolean(page.props.auth?.user))

const loading = ref(false)
const postItems = ref([...props.posts.data])
const visibilityTrigger = ref(null)
const hasMorePages = ref(Boolean(props.posts.next_page_url))
const showLoadMoreButton = ref(false)
const MAX_AUTO_LOAD_PAGES = 3

const socialLinks = [
  { name: 'X', href: '#', icon: XIcon },
  { name: 'Instagram', href: '#', icon: InstagramIcon },
  { name: 'GitHub', href: 'https://github.com', icon: GitHubIcon },
  { name: 'LinkedIn', href: '#', icon: LinkedInIcon },
]

const mappedArticles = computed(() =>
  postItems.value.map((post) => ({
    id: post.id,
    slug: post.slug,
    title: post.title,
    description: post.excerpt,
    date: post.published_at,
    href: route('blog.posts.show', post.slug, false),
    cta: '阅读全文',
  })),
)

watch(
  () => props.posts,
  (newPosts) => {
    if (Array.isArray(newPosts.data) && newPosts.data.length > 0) {
      const existingIds = new Set(postItems.value.map((item) => item.id))
      const uniqueNewPosts = newPosts.data.filter((post) => !existingIds.has(post.id))
        
      if (newPosts.current_page === 1) {
        postItems.value = [...newPosts.data]
      } else {
        postItems.value = [...postItems.value, ...uniqueNewPosts]
      }
    }

    hasMorePages.value = Boolean(newPosts.next_page_url)

    if ((newPosts.current_page ?? 1) >= MAX_AUTO_LOAD_PAGES) {
        showLoadMoreButton.value = true
    }
    
    loading.value = false
  },
  { deep: true },
)

const loadMore = () => {
  if (loading.value || !hasMorePages.value || !props.posts.next_page_url) {
    return
  }
    
    loading.value = true
    
  router.get(
    props.posts.next_page_url,
    {},
    {
        preserveState: true,
        preserveScroll: true,
        only: ['posts'],
      onError: () => {
            loading.value = false
        },
    },
  )
}

const handleVisibilityChange = (entry) => {
  if (
    entry.isIntersecting &&
        !loading.value && 
        hasMorePages.value && 
        !showLoadMoreButton.value && 
    (props.posts.current_page ?? 1) < MAX_AUTO_LOAD_PAGES
  ) {
        loadMore()
    }
}

let observer = null

onMounted(() => {
  if ((props.posts.current_page ?? 1) >= MAX_AUTO_LOAD_PAGES) {
        showLoadMoreButton.value = true
    }

  observer = new IntersectionObserver(
        (entries) => {
            handleVisibilityChange(entries[0])
        },
    { threshold: 0.1, rootMargin: '200px' },
    )
    
    if (visibilityTrigger.value) {
        observer.observe(visibilityTrigger.value)
    }
})
    
    onUnmounted(() => {
  if (observer) {
        observer.disconnect()
    observer = null
  }
})
</script>

<template>
  <SpotlightLayout title="博客">
        <Head title="博客" />

    <Container class="mt-12 sm:mt-16">
      <PageHero
        max-width="max-w-2xl"
        title="记录我在技术与生活之间往返的真实故事。"
        description="这是我的个人博客，既有学习笔记，也有创作灵感、生活随记与偶尔的感悟。希望这里的文字能与你产生一点点共鸣。"
      >
        <div class="flex flex-wrap gap-6 text-zinc-600 dark:text-zinc-400">
          <SocialLink
            v-for="item in socialLinks"
            :key="item.name"
            :href="item.href"
            :icon="item.icon"
          />
                        </div>
                        
        <div v-if="canCreatePost">
          <Button :href="route('author.posts.create')" className="px-4 py-2">
            <PlusIcon class="h-4 w-4" />
            <span class="ml-2">写文章</span>
          </Button>
        </div>
      </PageHero>
    </Container>

    <Photos />

    <Container class="mt-24 md:mt-28">
      <div class="mx-auto grid max-w-xl grid-cols-1 gap-y-20 lg:max-w-none lg:grid-cols-[minmax(0,2fr)_minmax(260px,1fr)] lg:gap-x-16">
        <div class="flex flex-col gap-16">
          <template v-if="mappedArticles.length">
            <ArticleCard
              v-for="article in mappedArticles"
              :key="article.id"
              :article="article"
            />
          </template>
          <p v-else class="text-sm text-zinc-500 dark:text-zinc-400">
            暂无文章，稍后再来看看吧。
          </p>
                                            </div>

        <div class="space-y-10 lg:pl-8">
          <Newsletter />
          <!-- <Resume /> -->
                                        </div>
                                    </div>
    </Container>

    <div
      v-if="hasMorePages"
      class="mx-auto mt-16 flex max-w-2xl flex-col items-center gap-4 px-6 pb-16 text-sm text-zinc-500 dark:text-zinc-400"
    >
      <div v-if="!showLoadMoreButton" ref="visibilityTrigger" class="h-10 w-full" />
      <LoadingSpinner v-if="loading" size="md" text="正在加载更多文章..." />
      <Button
        v-else
        variant="secondary"
        className="w-full justify-center"
                                    @click="loadMore"
                                >
                                    加载更多文章
      </Button>
                            </div>
  </SpotlightLayout>
</template>
